package com.oa.ylms.apps.dao.archives.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.oa.ylms.apps.dao.archives.IRPInfoDao;
import com.oa.ylms.apps.entity.archives.RPCategoryValue;
import com.oa.ylms.apps.entity.archives.RPInfoValue;

public class RPInfoDaoImpl extends HibernateDaoSupport implements IRPInfoDao {
	List<RPInfoValue> list;

	@Override
	public int addRPInfo(RPInfoValue rpInfo) throws Exception {
		if(rpInfo != null){
			this.getHibernateTemplate().save(rpInfo);
			return rpInfo.getRpId();
		}
		return 0;
	}

	@Override
	public boolean deleteRPInfo(RPInfoValue rpInfo) throws Exception {
		if(rpInfo != null){
			try{
				this.getHibernateTemplate().delete(rpInfo);
			}catch(Exception e){
				return false;
			}
			return true;
		}
		return false;
	}

	@Override
	public boolean modifyRPInfo(RPInfoValue rpInfo) throws Exception {
		if(rpInfo != null){
			try{
				this.getHibernateTemplate().update(rpInfo);
			}catch(Exception e){
				return false;
			}
			return true;
		}
		return false;
	}

	@Override
	public RPInfoValue queryByRPId(RPInfoValue rpInfo) throws Exception {
		if(rpInfo != null){
			return (RPInfoValue) this.getHibernateTemplate().get(RPInfoValue.class, rpInfo.getRpId());
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<RPInfoValue> queryRPInfo(final RPInfoValue rpInfo, final RPCategoryValue rpCategory) throws Exception {
		if(rpInfo != null){
			String hqlStr = "SELECT rpiv FROM RPInfoValue rpiv, RPCategoryValue rpcv WHERE 1=1 AND rpiv.rpCategory.categoryId = rpcv.categoryId";
			if(rpInfo.getRpCategory() != null){
				hqlStr += " AND rpiv.rpCategory = ?";
			}
			if(rpCategory.getIsRP() != null){
				hqlStr += " AND rpcv.isRP = ?";
			}
			if(rpInfo.getArchiveInfo() != null){
				hqlStr += " AND rpiv.archiveInfo = ?";
			}
			final String hql = hqlStr;
			list = this.getHibernateTemplate().executeFind(new HibernateCallback() {
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					Query query = session.createQuery(hql);
					int index = -1;
					if(rpInfo.getRpCategory() != null){
						query.setEntity(++index, rpInfo.getRpCategory());
					}
					if(rpCategory.getIsRP() != null){
						query.setInteger(++index, rpCategory.getIsRP());
					}
					if(rpInfo.getArchiveInfo() != null){
						query.setEntity(++index, rpInfo.getArchiveInfo());
					}
					list = query.list();
					return list;
				}
			});
			return list;
		}
		return null;
	}
	
	public List<RPInfoValue> getList() {
		return list;
	}

	public void setList(List<RPInfoValue> list) {
		this.list = list;
	}

}
